<template>
  <div class="update-name">
    <van-nav-bar
      title="设置昵称"
      left-text="取消"
      right-text="完成"
      @click-left="$emit('close')"
      @click-right="onConfirm"
    />
    <div class="field-wrap">
      <van-field
        v-model.trim="localName"
        rows="2"
        autosize
        type="textarea"
        maxlength="20"
        placeholder="请输入昵称"
        show-word-limit
      />
    </div>
  </div>
</template>

<script>
import { updateUserProfile } from '@/api/user.js'
export default {
  name: 'UpdateName',
  components: {},
  props: {
    value: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      localName: ''
    }
  },
  computed: {},
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async onConfirm() {
      try {
        // 防止网络慢导致的持续点击
        this.$toast.loading({
          message: '保存中...',
          forbidClick: true, // 禁止背景点击
          duration: 0 // 持续展示
        })
        const localNameText = this.localName
        if (!localNameText.length) {
          this.$toast('昵称不能为空')
          return alert('请重新输入')
        }

        const { data } = await updateUserProfile({
          name: localNameText
        })

        // 更新视图
        this.$emit('input', localNameText)

        // 关闭弹窗
        this.$emit('close')

        // 提示成功
        this.$toast.success('更新成功')
        console.log('改昵称', data)
      } catch (error) {
        this.$toast.fail('更新失败')
      }
    }
  }
}
</script>

<style acoped lang="less">
.field-wrap {
  padding: 10px;
}
</style>
